package com.gzu.ltms.filter;

import com.gzu.ltms.constant.RedisKeyConstants;
import com.gzu.ltms.holder.LoginUserContextHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
@Order(1)
public class AddUserId2HeaderFilter implements Filter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Header 头中 Token 的 Key
     */
    private static final String TOKEN_HEADER_KEY = "Authorization";

    /**
     * Token 前缀
     */
    private static final String TOKEN_HEADER_VALUE_PREFIX = "Bearer ";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        log.info("==================> TokenConvertFilter");

        // 从请求头中获取 Token 数据
        String authorization = httpServletRequest.getHeader(TOKEN_HEADER_KEY);


        if (StringUtils.isBlank(authorization)) {
            // 若请求头中未携带 Token，则直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

        // 将 Token 前缀去除
        String token = authorization.replace(TOKEN_HEADER_VALUE_PREFIX, "");

        // 构建 Redis Key
        String tokenRedisKey = RedisKeyConstants.SA_TOKEN_TOKEN_KEY_PREFIX + token;
        // 查询 Redis, 获取用户 ID
        Object userId = redisTemplate.opsForValue().get(tokenRedisKey);

        if (Objects.isNull(userId)) {

            // 若没有登录，则直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

        log.info("## 当前登录的用户 ID: {}", userId);

        LoginUserContextHolder.setUserId(userId);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
